package com.xzavier.yunlian_interview.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzavier.yunlian_interview.entity.ApifoxModel;
import com.xzavier.yunlian_interview.entity.QuestionItem;
import com.xzavier.yunlian_interview.mapper.QuestionItemMapper;
import com.xzavier.yunlian_interview.service.QuestionItemService;
import com.xzavier.yunlian_interview.service.ex.QuestionRecordException;
import com.xzavier.yunlian_interview.utils.QuestionTotal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuestionItemServiceImpl implements QuestionItemService {
    @Autowired
    private QuestionItemMapper questionItemMapper;

    @Override
    public QuestionTotal getQuestionTotal(ApifoxModel apifoxModel) {
        QuestionTotal questionTotal = new QuestionTotal();
        Page<QuestionItem> page = new Page<>(apifoxModel.getPage(), apifoxModel.getPageSize());
        QueryWrapper<QuestionItem> wrapper = new QueryWrapper<>();
        if (apifoxModel.getKeyword().isEmpty()) {
            apifoxModel.setKeyword("其他");
        }
        wrapper.like("stem", "其他".equals(apifoxModel.getKeyword()) ? "" : apifoxModel.getKeyword());
        wrapper.eq("questionBankType", apifoxModel.getQuestionBankType());
        questionTotal.setTotal(questionItemMapper.selectList(wrapper).size());
        Integer PageTotal = questionTotal.getTotal() / apifoxModel.getPageSize();
        questionTotal.setPageTotal(PageTotal);
        if (apifoxModel.getPage() > apifoxModel.getPageSize()) {
            return questionTotal;
        }
        if (apifoxModel.getSort().equals("10")) {
            wrapper.orderByAsc("difficulty");
        } else if (apifoxModel.getSort().equals("11")) {
            wrapper.orderByDesc("difficulty");
        } else if (apifoxModel.getSort().equals("20")) {
            wrapper.orderByAsc("views");
        } else if (apifoxModel.getSort().equals("21")) {
            wrapper.orderByDesc("views");
        } else if (apifoxModel.getSort().equals("30")) {
            wrapper.orderByDesc("likeCount");
        }
        Page<QuestionItem> page1 = questionItemMapper.selectPage(page, wrapper);
        questionTotal.setRows(page1.getRecords());
        return questionTotal;
    }

    @Override
    public QuestionItem getQuestionItem(String questionId) {
        QueryWrapper<QuestionItem> wrapper = new QueryWrapper<>();
        wrapper.eq("id", questionId);
        QuestionItem questionItem = questionItemMapper.selectOne(wrapper);
        if (questionItem == null) {
            throw new QuestionRecordException("题目无记录");
        }
        return questionItem;

    }
}
